﻿using SLAssetSystem;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public static class ConfigToCodeUtils {

    public enum FileType {
        CSV=0,
    }

    static string infosTemplate;
    static string infoTemplate;


    public static void GetCodeByFilePath(FileType type,string filePath,string fileName, out string infos, out string info)
    {
        if (string.IsNullOrEmpty(infosTemplate))
        {
            string path = Application.dataPath + "/Editor/Scripts/Systems/AssetSystem/Template/InfosTemplate.cs";
            infosTemplate = File.ReadAllText(path);
        }

        if (string.IsNullOrEmpty(infoTemplate))
        {
            string path = Application.dataPath + "/Editor/Scripts/Systems/AssetSystem/Template/infoTemplate.cs";
            infoTemplate = File.ReadAllText(path);
        }

        infos = "";
        info = "";
        switch (type)
        {
            case FileType.CSV:
                GetCodeByCSVFile(filePath, fileName,out infos, out info);
                break;
            default:
                break;
        }

    }

    static string infosContentTemplate = "            info.{Key} = data.Get{Type}(i,\"{Key}\");";
    static string infoContentTemplate = "    public {Type} {Key};";
    public static void GetCodeByCSVFile(string filePath, string fileName ,out string infos,out string info)
    {
        infos = "";
        info = "";

        filePath = AssetPaths.GetResourcesPath(filePath);
        fileName = AssetPaths.GetFileWithoutExtension(fileName);

        CsvData data = AssetSystem.Inst.LoadResAsset<CsvData>(filePath, fileName, AssetType.CSV);
        infos = infosTemplate.Replace("InfosTemplate", fileName + "Infos");
        infos = infos.Replace("InfoTemplate", fileName + "Info");
        info = infoTemplate.Replace("InfoTemplate", fileName + "Info");


        Dictionary<string, int> k2is = data.GetKeys();
        string infosContent = "";
        string infoContent = "";

        foreach (var k2i in k2is)
        {
            if (k2i.Key != "ID") 
            {
                infosContent = infosContent + "\r\n" + infosContentTemplate.Replace("{Key}", k2i.Key).Replace("{Type}",  data.GetTypeByKey(k2i.Key).Replace("[]","Array"));
                infoContent = infoContent + "\r\n" + infoContentTemplate.Replace("{Key}", k2i.Key).Replace("{Type}", data.GetTypeByKey(k2i.Key).ToLower());
            }
        }

        infos = infos.Replace("//Content", infosContent);
        info = info.Replace("//Content", infoContent);
        DebugUtils.Log(infos);
        DebugUtils.Log(info);
    }
}
